<template>
  <t-dialog
    v-model:visible="visible"
    :close-on-overlay-click="false"
    :close-on-esc-keydown="false"
    header="复制参数"
    class="common-dialog"
    @confirm="handleConfirm"
  >
    <t-checkbox v-model="checkAll" :indeterminate="indeterminate" :on-change="handleSelectAll" label="全选" />
    <t-checkbox-group v-model="checkValue" class="checkbox-wrap">
      <div class="checkbox-box">
        <t-row :gutter="[0, 10]">
          <t-col v-for="item in list" :key="item.value" :span="3">
            <t-checkbox
              class="checkbox-item"
              :value="item.value"
              :disabled="item.disabled"
              :on-change="handleSelectItem"
            >
              {{ item.label }}
            </t-checkbox>
          </t-col>
        </t-row>
      </div>
    </t-checkbox-group>
  </t-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';

const props = defineProps({
  index: {
    type: Number,
    default: -1,
  },
});

const emits = defineEmits(['sure']);

const visible = ref(false);

const checkValue = ref([]);
const checkAll = ref(false);

const list = ref([
  { label: '星期一', value: 0, disabled: false },
  { label: '星期二', value: 1, disabled: false },
  { label: '星期三', value: 2, disabled: false },
  { label: '星期四', value: 3, disabled: false },
  { label: '星期五', value: 4, disabled: false },
  { label: '星期六', value: 5, disabled: false },
  { label: '星期日', value: 6, disabled: false },
]);

watch(
  () => props.index,
  (num) => {
    list.value = list.value.map((item: any) => {
      item.disabled = item.value === num;
      return item;
    });
  },
  { immediate: true },
);

const indeterminate = computed(() => {
  const len = checkValue.value.length;
  return len !== 0 && len !== list.value.length - 1;
});

const handleSelectAll = () => {
  checkValue.value = checkAll.value
    ? list.value.filter((item: any) => item.value !== props.index).map((item: any) => item.value)
    : [];
};

const handleSelectItem = () => {
  checkAll.value = checkValue.value.length === list.value.length - 2;
};

const handleConfirm = () => {
  close();
  emits('sure', checkValue.value);
};

const open = () => {
  visible.value = true;
  checkValue.value = [];
};

const close = () => {
  visible.value = false;
};

defineExpose({ open, close });
</script>

<style lang="less" scoped>
.checkbox-wrap {
  display: flex;
  flex-direction: column;
  gap: 0;

  .t-checkbox {
    margin-bottom: 6px;
  }

  .checkbox-box {
    margin-top: 10px;
  }
}
</style>
